<?php
/**
 * Created by 长毋相忘c.
 * 文件用途描述 :
 * Date: 2018/2/18/018
 * Time: 22:10
 */

namespace app\api\controller\v1;


use app\api\controller\BaseController;
use app\api\model\User as UserModel;
use app\api\model\UserAddress;
use app\api\service\Token as TokenService;
use app\api\validate\AddressNew;
use app\lib\exception\SuccessMessage;
use app\lib\exception\UserException;

class AddressController extends BaseController
{
    protected $beforeActionList=[
          'checkExclusiveScope'=>['only'=>'createOrUpdateAddress,getUserAddress']
    ];



    public function second(){
        echo 'second';
    }

    public function third(){
        echo 'third';
    }

    public function createOrUpdateAddress(){
       $validate= new AddressNew();
        $validate ->goCheck();
        //根据Token来获取uid
        $uid=TokenService::getCurrentUid();
        //根据uid查询用户数据，判断用户是否存在，如果不存在抛出异常
        $user=UserModel::get($uid);
        if(!$user){
            throw new UserException();
        }
        //获取用户从客户端传来的地址信息 $dataArray=$validate->getDataByRule(input('post.'));
        $dataArray=$validate->getDataByRule(input('post.'));
        //根据用户地址信息是否存在从而判断是添加地址还是更新地址
        $userAddress=$user->address;
        if (!$userAddress){
            $user->address()->save($dataArray);
        }else{
            $user->address->save($dataArray);
        }
        //更改返回状态码201
        return json(new SuccessMessage(),201);
    }

    public function getUserAddress(){
        $uid = TokenService::getCurrentUid();
        $userAddress=UserAddress::where('user_id',$uid)->find();
        if(!$userAddress){
            throw new UserException([
                'msg'=>'用户地址不存在',
                'errorCode'=>60001
            ]);
        }
        return $userAddress;
    }
}